package com.qf.mvc2202.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.mvc2202.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 演示 json 处理
 */
@RestController
@RequestMapping("/json")
public class JsonController {

    @RequestMapping("/get/{id}")
    public User getUser(@PathVariable("id") Integer id){

        //1 调用servic查找user
        final User user = new User();
        user.setName("luffy");
        user.setId(id);

        //2 返回user
        return user;

    }


    @RequestMapping("/getAll")
    public List<User> getUsers(Integer pageNum,Integer size){

        // 调用service进行分页查询

        final User user1 = new User();
        user1.setName("luffy");
        user1.setId(100);
        final User user2 = new User();
        user2.setName("luffy");
        user2.setId(200);

        final List<User> users = Arrays.asList(user1, user2);

        return users;

    }

    @RequestMapping(value = "/str")
    public String testReturnString(){
        System.out.println("==========");

        return "{\"name\":\"zhangs\"}";
    }


    /**
     * @RequestBody 的作用， 把请求体中的字符串转换成参数对应类型的对象
     * @param user
     * @return
     */
    @RequestMapping("/add")
    public User addUser(@RequestBody User user){
        System.out.println(user);
        user.setId(200);
        return user;
    }

    /**
     * 测试 @RequestBody 修饰String类型的参数
     * @param userjson
     * @return
     */
    @RequestMapping("/update")
    public User updateUser(@RequestBody String userjson) throws IOException {
        System.out.println(userjson);

        //  jackson类库中的 json核心对象
        final ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(userjson, User.class);

        user.setId(200);
        return user;
    }
}
